package com.bijiawang.user.service;

import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class EmailService {

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Value("${spring.mail.username}")
    String emailFrom;

    public void sendEmail(String email) throws UnsupportedEncodingException {
        String code = randomCode();
        stringRedisTemplate.opsForValue().set(email, code,5, TimeUnit.MINUTES);
        SimpleMailMessage Message = new SimpleMailMessage();
        Message.setSubject("验证码");
        Message.setText("您的验证码是：" + code + ",5分钟内有效");
        Message.setTo(email);
        String fromtext =new String(("比价网<"+ emailFrom + ">").getBytes(StandardCharsets.UTF_8));
        Message.setFrom(fromtext);
        javaMailSender.send(Message);
    }

    public String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}
